package controller

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"strings"
)

// CheckSensitiveWords 检查字符串是否包含敏感词
func CheckSensitiveWords(content string) bool {
	// 从文件加载敏感词列表
	sensitiveWords, err := loadSensitiveWords("./pkg/sensitivewords/广告.txt")
	if err != nil {
		fmt.Println("Error loading sensitive words:", err)
		// 加载敏感词文件失败，返回false
		return false
	}

	fmt.Println("Loaded sensitive words:", sensitiveWords)

	// 检查帖子内容是否包含敏感词
	for _, word := range sensitiveWords {
		// 移除 \b 边界匹配，直接进行字符串包含检查
		re := regexp.MustCompile(regexp.QuoteMeta(word))
		if re.MatchString(content) {
			// 包含敏感词，返回true
			return true
		}
	}

	// 不包含敏感词，返回false
	return false
}

// loadSensitiveWords 从文件加载敏感词列表
func loadSensitiveWords(filename string) ([]string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	var sensitiveWords []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		word := strings.TrimSpace(scanner.Text())
		if word != "" {
			sensitiveWords = append(sensitiveWords, word)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return sensitiveWords, nil
}
